package com.fast.alden.common.service.impl;

import com.fast.alden.common.entity.vo.MailEntity;
import com.fast.alden.common.exception.BizException;
import com.fast.alden.common.service.MailService;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MailServiceImpl implements MailService {
    @Resource
    private JavaMailSender sender;
    @Value("${spring.mail.username}")
    private String senderAccount;

    @Override
    public void send(MailEntity mail) {
        List<MimeMessage> messages = mail.getReceivers().stream().map(receiver -> {
            MimeMessage message = sender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message);

            try {
                helper.setFrom(senderAccount);
                helper.setTo(receiver);
                helper.setSubject(mail.getSubject());
                helper.setText(mail.getContent());
            } catch (MessagingException e) {
                throw new BizException(e);
            }

            return message;
        }).toList();

        sender.send(messages.toArray(new MimeMessage[0]));
    }
}
